package com.tpl.core.basedata.action.sys;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import com.tpl.core.JsonUtil;
import com.tpl.core.action.BaseAction;
import com.tpl.core.action.SessionUtil;
import com.tpl.core.basedata.service.sys.FileService;
import com.tpl.core.common.Config;
import com.tpl.core.common.DateUtil;
import com.tpl.core.common.MD5FileUtil;
import com.tpl.core.common.TreeHelper;
import com.tpl.core.common.constant.IConstants;
import com.tpl.core.common.exception.RuleException;
import com.tpl.core.entity.sys.Files;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;


/**
 * 文件管理
 * @author 狄敏
 * @version 创建时间：2013-12-17 下午5:46:18 
 *
 */
@Controller
@RequestMapping("/file")
public class FileAction extends BaseAction {
	
	private static final long serialVersionUID = -2079920179375430877L;
	@Autowired
	private FileService fileService;
	private Boolean pubFlag;
	private static final String rootIds=","+ Config.getString("file.root.ids")+",";
	

	@Override
	protected void setOtherRequest() {
		super.setOtherRequest(); 
		pubFlag=StringUtils.isNotEmpty(getStrParameter("pubFlag"));
	}
	/**
	 * 跳转到文件管理页面
	 * 管理员登录需要在链接后加pubFlag=?
	 * 如果需要选中某个文件，在链接后+id=?;
	 * @return
	 */
	@RequestMapping("/toFile.do")
	public String toFile(Long id){
		putInRequest("selectId", id,"param_key", getStrParameter("param_key"),"chkStyle", getStrParameter("chkStyle"));
		if(pubFlag)
			return "file/file_manage";
		else
			return "file/file_user";
	}
	
	/**
	 * 获取文件夹树
	 */
	@RequestMapping("/getTree.do")
	public @ResponseBody void getFileTree(){
		Long deptId= SessionUtil.getLoginDeptId();
		List<Files> list=fileService.getDirList(pubFlag?null: SessionUtil.getLoginUserNo(), "2", deptId);
		TreeHelper tree=new TreeHelper(new String[]{"id","sourceName","parentId","pubFlag","fileName","path"},list,2) {
			@Override
			public Object root() {
				return -1;
			}
			@Override
			public Object[] idTextData(Object[] nodeData) {
				return new Object[]{nodeData[0],nodeData[1]};
			}
		};
		outJson(tree);
	}
	
	/**
	 * 通过文件夹获取资源
	 */
	@RequestMapping("/getFileById.do")
	public @ResponseBody void getFileById(Long pid){
		Long deptId= SessionUtil.getLoginDeptId();
		List<Files> list = null;
		if(0==pid){ //获取回收站内容
			list = fileService.getRecycleBinFileById(pubFlag, deptId);
		}else{ //获取对应文件夹的内容
			list = fileService.getFileById(pid, deptId);
		}
		outJsonSuccess(JsonUtil.toJSONArray(list).toString());
	}
	
	
	/**
	 * 新增文件夹
	 */
	@RequestMapping("/addDir.do")
	public @ResponseBody void addDir(Long pid){
		Files f = fileService.saveDir(pid, pubFlag);
		outJsonSuccess(JsonUtil.toJSONObject(f).toString());
	}
	
	/**
	 * 上传
	 * @param pid
	 * @throws IOException
	 */
	@RequestMapping("/upload.do")
	public @ResponseBody void upload (Long pid){
		CommonsMultipartFile srcFile=(CommonsMultipartFile)((DefaultMultipartHttpServletRequest)getRequest()).getFile("file");
		try {
			Files file=upload(pid, srcFile);
			outJsonSuccess(JsonUtil.toJSONObject(file).toString());
		} catch (Exception e) {
			outJsonFailure(e.getMessage());
		}
	}
	protected Files upload(Long pid, CommonsMultipartFile srcFile)
			throws IOException {
		String sourceName = srcFile.getOriginalFilename();
		Long fileSize = srcFile.getSize();
		Long size=IConstants.UPLOAD_FILE_SIZE/(1024*1024);
		if(IConstants.UPLOAD_FILE_SIZE>0&&IConstants.UPLOAD_FILE_SIZE<fileSize)
			throw new RuleException("上传文件大于"+size+"M，超过上限");
		String dateTime = DateUtil.formatUserDefineDate(new Date(),	"yyyyMMdd");
		if (pid == null) { // 当没有当前登录人的文件夹时，新建
			Files f = fileService.saveUserDir();
			pid = f.getId();
		}
		Files pfile=fileService.getFilesById(pid);
		String path = pfile.getPath()+pfile.getFileName()+"/";//fileService.getDirPath(pid);
		try {
			if(rootIds.indexOf(","+pfile.getParentId()+",")!=-1)
				path+=(SessionUtil.getLoginDept().getDeptNo())+"/";
		} catch (Exception e) {
		}
		path+=DateUtil.formatUserDefineDate(new Date(), "yyyyMM")+"/";//按月分离
		String absolutePath = getRealPath(path);

		// String absolutePath = request.getRealPath(path);
		InputStream instream = srcFile.getInputStream();
		FileOutputStream fos = null;
		try {
			String md5 = "";
			if (instream instanceof FileInputStream)
				md5 = MD5FileUtil.getFileMD5String((FileInputStream) instream,	fileSize);
			else
				md5 = MD5FileUtil.getMD5String(srcFile.getFileItem().get());
			Files file = fileService.getFilesByMd5(md5);
			// md5未匹配
			if (file == null) {
				String fileName = dateTime + md5 + sourceName.substring(sourceName.lastIndexOf("."));
				File _file = new File(absolutePath);
				if (!_file.exists()) {
					_file.mkdirs();
				}
				File savefile = new File(new File(absolutePath), fileName);
				// 建立文件输出流
				fos = new FileOutputStream(savefile);
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = instream.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
				file = new Files();
				file.setFileSize(fileSize);
				file.setMd5(md5);
				file.setPath(path);
				file.setFileName(fileName);
			} else {// 存在重复文件
					// 判断同一文件下是否有md5相同，原文件名相同的文件
				if (fileService.isRepeat(pid, sourceName, md5)) {
					return file;
				}
				file.setCopy(file.getId());
			}

			file.setSourceName(sourceName);
			file.setFileSuffix(sourceName.substring(sourceName.lastIndexOf(".") + 1));
			try {
				file.setCreator(SessionUtil.getLoginUserNo());
				file.setDeptId(SessionUtil.getLoginDeptId());
			} catch (Exception e) {
			}
			file.setCreateDate(DateUtil.now());
			file.setUpdateDate(file.getCreateDate());
			file.setUpdator(file.getCreator());
			file.setParentId(pid);
			file.setFileType(1);
			file.setPubFlag(pubFlag ? 1 : 0);
			file.setState(1);
			fileService.saveFile(file);
			return file;
		} catch (Exception e) {
			throw new RuleException("上传文件失败");
		} finally {
			if (instream != null) {
				instream.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
	}
	
	@RequestMapping("/batchUpload.do")
	public @ResponseBody void batchUpload(Long pid){
		List<MultipartFile> srcFiles=((DefaultMultipartHttpServletRequest)getRequest()).getFiles("file");
		try {
			JSONArray ja=new JSONArray();
			for(MultipartFile src:srcFiles){
				CommonsMultipartFile srcFile=(CommonsMultipartFile)src;
				Files file=upload(pid, srcFile);
				ja.add(file);
			}
			outJsonSuccess(ja.toString());
		} catch (Exception e) {
			outJsonFailure(e.getMessage());
		}
		
	}
	
	/**
	 * 修改文件夹名称
	 */
	@RequestMapping("/updateName.do")
	public @ResponseBody void updateName(Long id, Long pid, String sourceName){
		fileService.updateName(id,pid,sourceName);
		outJsonSuccess();
	}
	

	
	/**
	 * 删除文件夹
	 */
	@RequestMapping("/delDir.do")
	public @ResponseBody void delDir(Long id){
		fileService.delDirById(id);
		outJsonSuccess();
	}
	
	/**
	 * 修改资源状态
	 */
	@RequestMapping("/updateState.do")
	public @ResponseBody void updateState(String ids,String state){
		fileService.updateState(ids,state);
		outJsonSuccess();
	}
	

	/**
	 * 复制文件
	 * @param pid 目标文件夹
	 * @param ids 复制文件的id
	 * @param type 复制或剪切
	 * 
	 */
	@RequestMapping("/copyFiles.do")
	public @ResponseBody void copyFiles(Long pid,String ids,String type,String publicFlag){
		String message = fileService.updateFiles(pid,ids,type,publicFlag);
		outJsonSuccess(message);
	}
	
	/**
	 * 替换文件
	 */
	@RequestMapping("/replaceFiles.do")
	public @ResponseBody void replaceFiles(String ids,String type,String publicFlag){
		fileService.updateFiles(ids,type,publicFlag);
		outJsonSuccess();
	}
}


